package com.tencent.qf.team.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tencent.qf.mybatis.pojo.PageRequest;
import com.tencent.qf.mybatis.pojo.PageResult;
import com.tencent.qf.team.dal.DmAppSalesOrganizationalPerformance;
import com.tencent.qf.team.dal.DmAppSalesPerformanceDetail;
import com.tencent.qf.team.dal.DmAppSalesPersonalPerformance;
import com.tencent.qf.team.dao.DmAppSalesOrganizationalPerformanceDao;
import com.tencent.qf.team.dao.DmAppSalesPerformanceDetailDao;
import com.tencent.qf.team.dao.DmAppSalesPersonalPerformanceByRootNodeGroupDao;
import com.tencent.qf.team.dao.DmAppSalesPersonalPerformanceBySecondGroupDao;
import com.tencent.qf.team.dao.DmAppSalesPersonalPerformanceDao;
import com.tencent.qf.team.dto.request.PerformanceSummaryByUidRequest;
import com.tencent.qf.team.dto.request.PerformanceSummaryOrganizationalHeaderDataRequest;
import com.tencent.qf.team.dto.request.PerformanceSummaryOrganizationalListRequest;
import com.tencent.qf.team.dto.request.PerformanceSummaryPersonalByUidsRequest;
import com.tencent.qf.team.dto.request.PerformanceSummaryPersonalListRequest;
import com.tencent.qf.team.dto.request.PerformanceSummaryUserDetailRequest;
import com.tencent.qf.team.dto.response.PerformanceSummary;
import com.tencent.qf.team.dto.response.PerformanceSummaryPersonalListResponse;
import com.tencent.qf.team.service.PerformanceSummaryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class PerformanceSummaryServiceImpl implements PerformanceSummaryService {
    @Autowired
    private DmAppSalesPersonalPerformanceDao dmAppSalesPersonalPerformanceDao;
    @Autowired
    private DmAppSalesPersonalPerformanceByRootNodeGroupDao dmAppSalesPersonalPerformanceByRootNodeGroupDao;
    @Autowired
    private DmAppSalesPersonalPerformanceBySecondGroupDao dmAppSalesPersonalPerformanceBySecondGroupDao;
    @Autowired
    private DmAppSalesOrganizationalPerformanceDao dmAppSalesOrganizationalPerformanceDao;
    @Autowired
    private DmAppSalesPerformanceDetailDao dmAppSalesPerformanceDetailDao;

    /**
     * 数据-业绩汇总-个人业绩-列表
     *
     * @param request
     * @return
     */
    @Override
    public PageResult<PerformanceSummaryPersonalListResponse> personalList(
            PageRequest<PerformanceSummaryPersonalListRequest> request) {
        PageHelper.startPage(request.getPageNo(), request.getPageSize());
        PerformanceSummaryPersonalListRequest requestData = request.getData();

        List<DmAppSalesPersonalPerformance> data = this.personalListQueryDB(requestData);
        if (CollectionUtils.isEmpty(data)) {
            return PageResult.build(new PageInfo(data));
        }

        PageResult result = PageResult.build(new PageInfo(data));

        // 从表dm_app_sales_personal_performance_by_root_node_group、dm_app_sales_personal_performance_by_second_group 查询的数据没有导师和完整组织,
        // 这里对这种数据补充导师和组织链信息
        this.buildGroupIdPathGuideUid(data, requestData);

        List<PerformanceSummaryPersonalListResponse> list = new ArrayList<>();
        for (DmAppSalesPersonalPerformance e : data) {

            PerformanceSummaryPersonalListResponse item = new PerformanceSummaryPersonalListResponse();
            BeanUtils.copyProperties(e, item);
            item.setEstimateIncome(e.getPredictCommissionAmt());
            list.add(item);

            // 计算客单价
            if (StringUtils.isNotEmpty(request.getData().getSalesDateBegin()) && StringUtils.isNotEmpty(request.getData().getSalesDateEnd())) {
                //订单金额
                BigDecimal salesAmt = item.getSalesAmt();
                //订单数量
                Integer salesOrderNum = item.getSalesOrderNum();
                if (salesOrderNum == 0) {
                    item.setSalesAtv(BigDecimal.ZERO);
                    continue;
                }
                //客单价
                BigDecimal divide = salesAmt.divide(new BigDecimal(salesOrderNum), 2, RoundingMode.DOWN);
                item.setSalesAtv(divide);
            }
        }

        result.setList(list);
        return result;
    }

    private List<DmAppSalesPersonalPerformance> personalListQueryDB(PerformanceSummaryPersonalListRequest requestData) {
        Boolean queryGroup = false;
        if (StringUtils.isNotEmpty(requestData.getSalesDateBegin()) && StringUtils.isNotEmpty(requestData.getSalesDateEnd())) {
            queryGroup = true;
        }

        List<DmAppSalesPersonalPerformance> data;
        if (requestData.getQueryDetail() || StringUtils.isNotEmpty(requestData.getGuideUid()) || requestData.getExcludeGuideUidInfo()) {
            // 导师不为空或者uid不为空：查dm_app_sales_personal_performance
            if (queryGroup) {
                data = dmAppSalesPersonalPerformanceDao.personalListGroup(requestData);
            } else {
                data = dmAppSalesPersonalPerformanceDao.personalList(requestData);
            }
        } else if (StringUtils.isEmpty(requestData.getGroupIdPath()) && CollectionUtils.isEmpty(requestData.getGroupIdPathList())) {
            // 导师为空、uid为空、组织为空：查dm_app_sales_personal_performance_by_root_node_group
            if (queryGroup) {
                data = dmAppSalesPersonalPerformanceByRootNodeGroupDao.personalListGroup(requestData);
            } else {
                data = dmAppSalesPersonalPerformanceByRootNodeGroupDao.personalList(requestData);
            }
        } else {
            // 组织不为空：
            // 1、跟节点组织：查dm_app_sales_personal_performance_by_root_node_group
            // 2、一级组织：查dm_app_sales_personal_performance_by_second_group
            // 2、二级组织：查dm_app_sales_personal_performance_by_second_group
            // 3、其他节点：查dm_app_sales_personal_performance
            String groupIdPath = StringUtils.isNotEmpty(requestData.getGroupIdPath()) ? requestData.getGroupIdPath() : requestData.getGroupIdPathList().get(0);
            String[] split = groupIdPath.split(":");
            if (split.length == 1) {
                if (queryGroup) {
                    data = dmAppSalesPersonalPerformanceByRootNodeGroupDao.personalListGroup(requestData);
                } else {
                    data = dmAppSalesPersonalPerformanceByRootNodeGroupDao.personalList(requestData);
                }
            } else if (split.length == 2 || split.length == 3) {
                // 一级组织、二级组织
                if (queryGroup) {
                    data = dmAppSalesPersonalPerformanceBySecondGroupDao.personalListGroup(requestData);
                } else {
                    data = dmAppSalesPersonalPerformanceBySecondGroupDao.personalList(requestData);
                }
            } else {
                if (queryGroup) {
                    data = dmAppSalesPersonalPerformanceDao.personalListGroup(requestData);
                } else {
                    data = dmAppSalesPersonalPerformanceDao.personalList(requestData);
                }
            }
        }
        return data;
    }

    /**
     * 从表dm_app_sales_personal_performance_by_root_node_group、dm_app_sales_personal_performance_by_second_group 查询的数据没有导师和完整组织,
     * 这里对这种数据补充导师和组织链信息
     *
     * @param data
     * @param requestData
     */
    private void buildGroupIdPathGuideUid(List<DmAppSalesPersonalPerformance> data, PerformanceSummaryPersonalListRequest requestData) {
        Set<String> uids = new HashSet<>();
        for (DmAppSalesPersonalPerformance item : data) {
            if (item.getUidNum() == 1) {
                uids.add(item.getUid());
            }
        }
        if (CollectionUtils.isEmpty(uids)) {
            return;
        }
        PerformanceSummaryPersonalByUidsRequest uidsRequest = new PerformanceSummaryPersonalByUidsRequest();
        BeanUtils.copyProperties(requestData, uidsRequest);
        uidsRequest.setUids(uids);
        List<DmAppSalesPersonalPerformance> personalListByUids = dmAppSalesPersonalPerformanceDao.personalListByUids(uidsRequest);
        Map<String, DmAppSalesPersonalPerformance> map = personalListByUids.stream().collect(Collectors.toMap(DmAppSalesPersonalPerformance::getUid, e -> e, (v1, v2) -> {
            if (v1.getSalesDate().compareTo(v2.getSalesDate()) > 0) {
                return v1;
            }
            return v2;
        }));
        for (DmAppSalesPersonalPerformance item : data) {
            if (map.containsKey(item.getUid())) {
                DmAppSalesPersonalPerformance value = map.get(item.getUid());
                item.setGroupIdPath(value.getGroupIdPath());
                item.setGuideUid(value.getGuideUid());
            }
        }
    }

    /**
     * 数据-业绩汇总-组织业绩-列表
     *
     * @param request
     * @return
     */
    @Override
    public List<DmAppSalesOrganizationalPerformance> organizationalList(PerformanceSummaryOrganizationalListRequest request) {
        List<DmAppSalesOrganizationalPerformance> data = dmAppSalesOrganizationalPerformanceDao.organizationalList(request);
        if (CollectionUtils.isEmpty(data)) {
            return Collections.emptyList();
        }
        if (StringUtils.isNotEmpty(request.getSalesDateBegin()) && StringUtils.isNotEmpty(request.getSalesDateEnd())) {
            // groupId维度分组求和
            return this.groupByGroupId(data);
        }
        return data;
    }

    /**
     * 数据-业绩汇总-组织业绩-头部展示数据
     *
     * @param request
     * @return
     */
    @Override
    public List<DmAppSalesOrganizationalPerformance> organizationalHeaderData(PerformanceSummaryOrganizationalHeaderDataRequest request) {
        List<DmAppSalesOrganizationalPerformance> data = dmAppSalesOrganizationalPerformanceDao.organizationalHeaderData(request);
        if (CollectionUtils.isEmpty(data)) {
            return Collections.emptyList();
        }
        if (StringUtils.isNotEmpty(request.getSalesDateBegin()) && StringUtils.isNotEmpty(request.getSalesDateEnd())) {
            // groupId维度分组求和
            return this.groupByGroupId(data);
        }
        return data;
    }

    /**
     * groupId维度分组求和
     *
     * @param data
     * @return
     */
    private List<DmAppSalesOrganizationalPerformance> groupByGroupId(List<DmAppSalesOrganizationalPerformance> data) {
        Map<String, DmAppSalesOrganizationalPerformance> resultMap = new HashMap<>();
        for (DmAppSalesOrganizationalPerformance performance : data) {
            String key = performance.getSalesBelongType() + performance.getRootNodeGroupId()
                    + performance.getFirstGroupId() + performance.getSecondGroupId() + performance.getThirdGroupId();
            if (resultMap.containsKey(key)) {
                DmAppSalesOrganizationalPerformance value = resultMap.get(key);
                value.setSalesAmt(value.getSalesAmt().add(performance.getSalesAmt()));
                value.setSalesIncomeAmt(value.getSalesIncomeAmt().add(performance.getSalesIncomeAmt()));
                value.setSalesOrderNum(value.getSalesOrderNum() + performance.getSalesOrderNum());
                value.setSalesUserNum(value.getSalesUserNum() + performance.getSalesUserNum());
                value.setSalesSelfIncomeAmt(value.getSalesSelfIncomeAmt().add(performance.getSalesSelfIncomeAmt()));
                value.setSalesPromoteIncomeAmt(value.getSalesPromoteIncomeAmt().add(performance.getSalesPromoteIncomeAmt()));
                value.setSalesPlatformBalanceAmt(value.getSalesPlatformBalanceAmt().add(performance.getSalesPlatformBalanceAmt()));
                value.setUpdateTime(performance.getUpdateTime());
                value.setSalesIncomeAmtAll(value.getSalesIncomeAmtAll().add(performance.getSalesIncomeAmtAll()));
                value.setOverchargeSalesIncomeAmt(value.getOverchargeSalesIncomeAmt().add(performance.getOverchargeSalesIncomeAmt()));
                value.setPromoteIncomeAmtAll(value.getPromoteIncomeAmtAll().add(performance.getPromoteIncomeAmtAll()));
                value.setSelfIncomeAmtAll(value.getSelfIncomeAmtAll().add(performance.getSelfIncomeAmtAll()));
                value.setBaseIncomeAmt(value.getBaseIncomeAmt().add(performance.getBaseIncomeAmt()));
            } else {
                resultMap.put(key, performance);
            }
        }

        List<DmAppSalesOrganizationalPerformance> list = new ArrayList<>(resultMap.values());
        // 计算客单价
        for (DmAppSalesOrganizationalPerformance item : list) {
            //订单金额
            BigDecimal salesAmt = item.getSalesAmt();
            //订单数量
            Integer salesOrderNum = item.getSalesOrderNum();
            if (salesOrderNum == 0) {
                item.setSalesAtv(BigDecimal.ZERO);
                continue;
            }
            //客单价
            BigDecimal divide = salesAmt.divide(new BigDecimal(salesOrderNum), 2, RoundingMode.DOWN);
            item.setSalesAtv(divide);
        }
        return list;
    }

    /**
     * 用户详情-收益订单数据
     *
     * @param request
     * @return
     */
    @Override
    public List<DmAppSalesPerformanceDetail> userDetail(PerformanceSummaryUserDetailRequest request) {
        List<DmAppSalesPerformanceDetail> data = dmAppSalesPerformanceDetailDao.userDetail(request);
        return data;
    }

    /**
     * 用户详情-获取用户时间范围内的gmv
     *
     * @param request
     * @return
     */
    @Override
    public List<PerformanceSummary> queryUserPerformanceSummary(PerformanceSummaryByUidRequest request) {
        List<PerformanceSummary> data = dmAppSalesPerformanceDetailDao.queryUserPerformanceSummary(request);
        return data;
    }
}
